from newpro.views.base import BaseHandler
from newpro.db import db
from newpro.util.md5 import md5

class IndexHandler(BaseHandler):
    def get(self):
        roleid = 1
        sql = "select res.*,pres.name as pname from role_resource as rr left join resource as res on rr.resourceid=res.id  inner join resource as pres on res.pid=pres.id where rr.userid=%d" % (int(roleid))
        res = db.findAll(sql)

        reslist = []
        ids = []
        # 遍历查询结果
        for i in res:
            # 判断父类是否存在，不存在添加
            if i["pid"] not in ids:
                ids.append(i['pid'])
                reslist.append({"id": i["pid"], "name": i['pname'], "son": [{"id": i['id'], "name":i['name'], 'url':i['url']}]})
            else:
                #存在，查找父类，遍历父类用子类的pid对比
                for (index, p) in enumerate(reslist):
                    if i['pid'] == p['id']:
                        #将子类加到父类下
                        reslist[index]['son'].append({"id": i['id'], "name": i['name'], 'url': i['url']})
        data = {"code": 200, "menulist": reslist}
        self.write(data)

    def post(self):
        #管理员设置密码统一标准
        password = '123456'
        #登录时如果密码是初始密码，强制到修改密码页面，其他页面不能操作beforEach
        pwd = md5(password)
        mes = {"code": 1, 'pwd': pwd}
        self.write(mes)


